package com.lee.system;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.lee.base.BaseService;
import com.lee.page.PageDomain;
import com.lee.page.PageResult;
import com.lee.system.api.IUserService;
import com.lee.system.entity.Post;
import com.lee.system.entity.Role;
import com.lee.system.entity.User;
import com.lee.system.entity.UserPost;
import com.lee.system.entity.UserRole;
import com.lee.system.mapper.PostMapper;
import com.lee.system.mapper.RoleMapper;
import com.lee.system.mapper.UserMapper;
import com.lee.system.mapper.UserPostMapper;
import com.lee.system.mapper.UserRoleMapper;
import com.lee.utils.Convert;
import com.lee.utils.StringUtils;


/**
 * 用户 服务层实现
 * 
 * @author LiPengFei
 *
 */
@Service
public class UserServiceImpl extends BaseService implements IUserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private UserPostMapper userPostMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private PostMapper postMapper;

	/**
	 * 查询用户信息
	 * 
	 * @param userId
	 *            用户ID
	 * @return 用户信息
	 */
	@Override
	public User selectUserById(Long userId) {
		
		return userMapper.selectUserById(userId);
	}

	/**
	 * 分页查询用户列表
	 * 
	 * @param user
	 *            用户信息
	 * @return 用户集合
	 */
	@Override
	public PageResult selectUserList(User user,PageDomain pageDomain) {
		startPage(pageDomain);
		Page<User> page = (Page<User>)userMapper.selectUserList(user);
		return new PageResult(page.getTotal(),page.getResult());
	}

	/**
	 * 新增用户
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	public int insertUser(User user) {
		return userMapper.insertUser(user);
	}

	/**
	 * 修改用户
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	public int updateUser(User user) {
		return userMapper.updateUser(user);
	}

	/**
	 * 保存用户
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveUser(User user) {
		Long userId = user.getUserId();
		int rows = 0;
		if (StringUtils.isNotNull(userId)) {
			rows = userMapper.updateUser(user);
			userRoleMapper.deleteUserRoleByUserId(userId);
			insertUserRole(user);
			userPostMapper.deleteUserPostByUserId(userId);
			insertUserPost(user);
		} else {
			/*user.saltRandom();
			user.setPassword(passwordService.encryptPassword( user.getLoginName(),user.getPassword(), user.getSalt()));*/
			rows = userMapper.insertUser(user);
			insertUserPost(user);
			insertUserRole(user);
		}
		return rows;
	}
	
	public int restPassWord(User user){
	/*	user.saltRandom();
		user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));*/
		return userMapper.updateUser(user);
	}

	/**
	 * 删除用户对象
	 * 
	 * @param ids
	 *            需要删除的数据ID
	 * @return 结果
	 * @throws Exception
	 */
	@Override
	public int deleteUserByIds(String ids) throws Exception {
		Long[] userIds = Convert.toLongArray(ids);
		for (Long userId : userIds) {
			if (userId != null && userId == 1L) {
				throw new Exception("不允许删除超级管理员");
			}
		}
		return userMapper.deleteUserByIds(userIds);
	}

	/**
	 * 新增用户岗位信息
	 * 
	 * @param user
	 *            用户对象
	 */
	public void insertUserPost(User user) {
		// 新增用户与岗位管理
		List<UserPost> list = new ArrayList<UserPost>();
		for (Long postId : user.getPostIds()) {
			UserPost up = new UserPost();
			up.setUserId(user.getUserId());
			up.setPostId(postId);
			list.add(up);
		}
		if (list.size() > 0) {
			userPostMapper.batchUserPost(list);
		}
	}

	/**
	 * 新增用户角色信息
	 * 
	 * @param user
	 *            用户对象
	 */
	public void insertUserRole(User user) {
		// 新增用户与角色管理
		List<UserRole> list = new ArrayList<UserRole>();
		for (Long roleId : user.getRoleIds()) {
			UserRole ur = new UserRole();
			ur.setUserId(user.getUserId());
			ur.setRoleId(roleId);
			list.add(ur);
		}
		if (list.size() > 0) {
			userRoleMapper.batchUserRole(list);
		}
	}

	/**
	 * 校验用户名是否唯一
	 */
	public int checkLoginNameUnique(String loginName) {
		return userMapper.checkLoginNameUnique(loginName);
	}

	/**
	 * 校验邮箱是否唯一
	 */
	public boolean checkEmailUnique(User user) {
		if (user.getUserId() == null) {
			user.setUserId(-1L);
		}
		User info = userMapper.checkEmailUnique(user.getEmail());
		if (StringUtils.isNotNull(info) && StringUtils.isNotNull(info.getUserId())
				&& user.getUserId().longValue() != info.getUserId().longValue()) {
			return false;
		}

		return true;
	}

	/**
	 * 校验手机是否唯一
	 */
	public boolean checkPhoneUnique(User user) {
		if (user.getUserId() == null) {
			user.setUserId(-1L);
		}
		User info = userMapper.checkPhoneUnique(user.getPhonenumber());
		if (StringUtils.isNotNull(info) && StringUtils.isNotNull(info.getUserId())
				&& user.getUserId().longValue() != info.getUserId().longValue()) {
			return false;
		}
		return true;
	}

	/**
	 * 根据登陆账号查询用户信息
	 */
	@Override
	public User selectByLoginName(String loginName) {

		return userMapper.selectByLoginName(loginName);
	}
	/**
	 * 查询用户所属角色组
	 * @param userId
	 * @return
	 */
	@Override
	public String selectUserRoleGroup(Long userId) {
		List<Role> list = roleMapper.selectRolesByUserId(userId);
		StringBuffer str = new StringBuffer();
		for(Role role:list){
			str.append(role.getRoleName()).append(",");
		}
		if(StringUtils.isNotEmpty(str.toString())){
			return str.substring(0,str.length()-1);
		}
		
		return str.toString();
	}

	@Override
	public String selectUserPostGroup(Long userId) {
		List<Post> list = postMapper.selectPostsByUserId(userId);
		StringBuffer str = new StringBuffer();
		for(Post post:list){
			str.append(post.getPostName()).append(",");
		}
		if(StringUtils.isNotEmpty(str.toString())){
			return str.substring(0,str.length()-1);
		}
		return str.toString();
	}
	/**
	 * 根据条件查询用户
	 */
	@Override
	public List<User> selectUserList(User user) {
		List<User> list = userMapper.selectUserList(user);
		return list;
	}
}
